import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:kudos/core/utils/kudo_colors.dart';
import 'package:loading_animation_widget/loading_animation_widget.dart';
import '../../router/app_navigation_manager.dart';
import '../../state/global_state_initializer.dart';

class LaunchGatewayScreen extends StatefulWidget {
  const LaunchGatewayScreen({super.key});

  @override
  State<LaunchGatewayScreen> createState() => _LaunchGatewayScreenState();
}

class _LaunchGatewayScreenState extends State<LaunchGatewayScreen>
    with TickerProviderStateMixin {
  late AnimationController _fadeAnimationController;
  late AnimationController _scaleAnimationController;
  late AnimationController _rotationAnimationController;

  late Animation<double> _fadeInAnimation;
  late Animation<double> _scaleAnimation;
  late Animation<double> _rotationAnimation;

  @override
  void initState() {
    super.initState();
    _initializeAnimationControllers();
    _startLaunchSequence();
  }

  void _initializeAnimationControllers() {
    _fadeAnimationController = AnimationController(
      duration: const Duration(milliseconds: 1000),
      vsync: this,
    );

    _scaleAnimationController = AnimationController(
      duration: const Duration(milliseconds: 1500),
      vsync: this,
    );

    _rotationAnimationController = AnimationController(
      duration: const Duration(milliseconds: 2000),
      vsync: this,
    );

    _fadeInAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(
        parent: _fadeAnimationController,
        curve: Curves.easeInOut,
      ),
    );
    _scaleAnimation = Tween<double>(begin: 0.5, end: 1.0).animate(
      CurvedAnimation(
        parent: _scaleAnimationController,
        curve: Curves.elasticOut,
      ),
    );

    _rotationAnimation = Tween<double>(begin: -0.1, end: 0.1).animate(
      CurvedAnimation(
        parent: _rotationAnimationController,
        curve: Curves.easeInOut,
      ),
    );
  }

  void _startLaunchSequence() async {
    _fadeAnimationController.forward();

    await Future.delayed(const Duration(milliseconds: 200));
    _scaleAnimationController.forward();

    await Future.delayed(const Duration(milliseconds: 300));
    _rotationAnimationController.repeat(reverse: true);

    // 初始化全局状态
    await GlobalStateInitializer.initializeAllStates();

    await Future.delayed(const Duration(milliseconds: 2000));
    _navigateToMainContainer();
  }

  void _navigateToMainContainer() {
    if (mounted) {
      AppNavigationManager.navigateToMainContainer(context);
    }
  }

  @override
  void dispose() {
    _fadeAnimationController.dispose();
    _scaleAnimationController.dispose();
    _rotationAnimationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: _buildGradientBackground(),
        child: FadeTransition(
          opacity: _fadeInAnimation,
          child:
              [
                SizedBox(height: 80.h),

                [
                  _buildLogoSection(),

                  _buildProjectNameSection(),

                  _buildLoadingSection(),
                ].toColumn(mainAxisAlignment: MainAxisAlignment.center),

                const Spacer(flex: 2),
              ].toColumn().safeArea(),
        ),
      ),
    );
  }

  BoxDecoration _buildGradientBackground() {
    return const BoxDecoration(
      gradient: LinearGradient(
        begin: Alignment(0.50, 1.00),
        end: Alignment(0.50, 0.00),
        colors: [Color(0xFFD4F953), Color(0xFF74E3FF)],
      ),
    );
  }

  Widget _buildLogoSection() {
    return AnimatedBuilder(
      animation: _scaleAnimationController,
      builder: (context, child) {
        return ScaleTransition(
          scale: _scaleAnimation,
          child: AnimatedBuilder(
            animation: _rotationAnimationController,
            builder: (context, child) {
              return Transform.rotate(
                angle: _rotationAnimation.value,
                child: Container(
                  width: 120.w,
                  height: 120.w,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(20.r),
                    boxShadow: [
                      BoxShadow(
                        color: Colors.black.withValues(alpha: 0.2),
                        blurRadius: 15,
                        offset: const Offset(0, 8),
                      ),
                    ],
                  ),
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(20.r),
                    child: Image.asset(
                      'assets/images/logo.png',
                      width: 120.w,
                      height: 120.w,
                      fit: BoxFit.cover,
                      errorBuilder: (context, error, stackTrace) {
                        return Container(
                          width: 120.w,
                          height: 120.w,
                          decoration: BoxDecoration(
                            color: Colors.yellow.shade400,
                            borderRadius: BorderRadius.circular(20.r),
                          ),
                          child: Icon(
                            Icons.change_history,
                            size: 60.w,
                            color: Colors.red.shade600,
                          ),
                        );
                      },
                    ),
                  ),
                ),
              );
            },
          ),
        );
      },
    );
  }

  /// 构建项目名称区域
  Widget _buildProjectNameSection() {
    return Text('Kudos')
        .fontSize(32.sp)
        .fontWeight(FontWeight.w900)
        .textColor(KudoColors.black)
        .fontFamily(
          GoogleFonts.montserrat(fontWeight: FontWeight.w900).fontFamily,
        )
        .textShadow(
          color: KudoColors.yellow,
          blurRadius: 0,
          offset: const Offset(0, 4),
        )
        .paddingTop(30.h);
  }

  /// 构建加载区域
  Widget _buildLoadingSection() {
    return LoadingAnimationWidget.threeRotatingDots(
      color: Colors.white,
      size: 40.w,
    ).paddingTop(40.h);
  }
}
